﻿using System;
using Google.GData.Calendar;
using CommonFoundation.DataModel;
using Google.GData.Client;
using CommonFoundation;
using Google.GData.Extensions;
using CommonFoundation.DataSource;

namespace WHULive
{
    public class MyCalendar
    {
        private string googleID = String.Empty;
        private string password = String.Empty;

        private CalendarService service = new CalendarService("hibix-whulive-beta");

        public MyCalendar()
        {
            this.service.setUserCredentials(this.googleID, this.password);
        }

        public MyCalendar(string ID, string pwd)
        {
            this.googleID = ID;
            this.password = pwd;

            this.service.setUserCredentials(this.googleID, this.password);
        }

        public bool UpdateLesson(Lesson lesson)
        {
            bool result = true;

            try
            {
                foreach (Schedule schedule in lesson.Schedules)
                {
                    AtomEntry recurringEvent = CreateRecurringEvent(service, schedule, lesson);
                }
            }
            catch (Exception ex)
            {
                result = false;

                Log.WriteLog(ex.Message);
            }

            return result;
        }

        private EventEntry CreateRecurringEvent(CalendarService service,Schedule schedule, Lesson lesson)
        {
            DateTime startDateTime = new DateTime(2012, 2, 12);

            DateTime endDateTime = new DateTime (2012, 2, 12);

            for (int i = 0; i < schedule.StartWeek - 1; i++)
            {
                startDateTime = startDateTime.AddDays(7);
            }

            for (int i = 0; i<schedule.WeekDay; i++)
            {
                startDateTime = startDateTime.AddDays(1);
            }

            for (int i = 0; i < schedule.EndWeek - 1; i++)
            {
                endDateTime = endDateTime.AddDays(7);
            }

            for (int i = 0;  i < schedule.WeekDay; i++)
            {
                endDateTime = endDateTime.AddDays(1);
            }

            String recurData = String.Format(
              "DTSTART;TZID=Asia/Shanghai:{0}\r\n" +
              "DTEND;TZID=Asia/Shanghai:{1}\r\n" +
              "RRULE:FREQ=WEEKLY;BYDAY={2};COUNT={3}\r\n",
                this.convertToString(startDateTime) + this.getStartTime(schedule),
                this.convertToString(startDateTime) + this.getEndTime(schedule),
                this.getDayName(schedule.WeekDay),
                (schedule.EndWeek - schedule.StartWeek + 1).ToString() );

            return CreateEvent(service, schedule, lesson, recurData);
        }

        private string[] startTimes = new string[] { "0800", "0850", "0950", "1040", "1130", 
            "1315", "1405", "1455", "1545", "1640", "1730", "1900", "1950", "2040"};
        private string[] endTimes = new string[] { "0845", "0935", "1035", "1125", "1215",
            "14:00", "1450", "1540", "1630", "1725","1815", "1945", "2035", "2125"};

        private string getStartTime(Schedule schedule)
        {

            return String.Format("T{0}00", this.startTimes[schedule.StartTime - 1]);
        }

        private string getEndTime(Schedule schedule)
        {
            return String.Format("T{0}00", this.endTimes[schedule.EndTime - 1]);
        }

        private string getDayName(int day)
        {
            string result = Consts.WeekDayNames[day];

            return result.Substring(0, 2);
        }

        private string convertToString(DateTime dateTime)
        {
            return dateTime.Year.ToString() + this.getStringByInteger(dateTime.Month) + this.getStringByInteger(dateTime.Day);
        }

        private string getStringByInteger(int num)
        {
            if (num < 10)
            {
                return String.Format("0{0}", num.ToString());
            }

            return num.ToString();
        }

        private EventEntry CreateEvent(CalendarService service,Schedule schedule, Lesson lesson, string recurData)
        {
            EventEntry entry = new EventEntry();

            entry.Title.Text = lesson.LessonName;

            Where location = new Where();
            location.ValueString = schedule.Location;
            entry.Locations.Add(location);

            if (String.IsNullOrEmpty(recurData))
            {
                When eventTime = new When();
                eventTime.StartTime = DateTime.Now;
                eventTime.EndTime = eventTime.StartTime.AddMinutes(30);
                entry.Times.Add(eventTime);
            }
            else
            {
                Recurrence recurrence = new Recurrence();
                recurrence.Value = recurData;
                entry.Recurrence = recurrence;
            }

            Uri postUri = new Uri(feedUri);

            AtomEntry insertedEntry = service.Insert(postUri, entry);

            return (EventEntry)insertedEntry;
        }

        private string feedUri = @"https://www.google.com/calendar/feeds/default/private/full";
    }
}
